package ejercicio8;

import java.util.Random;
import java.util.concurrent.Semaphore;

public class Hemoterapia {
	
	static Semaphore cantCamillas = new Semaphore(4, true);
	static Semaphore cantRevistas = new Semaphore(10);

	public static class PersonaThread extends Thread {
		
		static Semaphore mutexR = new Semaphore(1, true);
		
		boolean tengoRevista = false;
		boolean estoyDonando = false;
		
		public void ocuparCamilla() throws InterruptedException{
			
			cantCamillas.acquireUninterruptibly();
			estoyDonando = true;
			mutexR.acquireUninterruptibly();
				if(tengoRevista){
					cantRevistas.release();
				}
				
			mutexR.release();
			
//			Thread.sleep(new Random().nextInt(5000)); // -- dona sangre
			
			cantCamillas.release();
		}
		
		public void esperarRevista() throws InterruptedException{
			cantRevistas.acquireUninterruptibly();
				if(! estoyDonando){
					cantRevistas.acquire();
				}else{
					tengoRevista = true;
				}
			mutexR.release();
		}
		
		@Override
		public void run() {			
			new EntrarSalaDeEsperaThread(this).start();
			new EntrarADonarThread(this).start();
		}
	}
	
	public static class EntrarADonarThread extends Thread {
		
		private PersonaThread persona;
		
		public EntrarADonarThread(PersonaThread persona0) {
			this.persona = persona0;
		}
		
		@Override
		public void run() {
			try { persona.ocuparCamilla(); } catch (InterruptedException e) { }			
		}
	}
	
	public static class EntrarSalaDeEsperaThread extends Thread {

		private PersonaThread persona;
		
		public EntrarSalaDeEsperaThread(PersonaThread persona0) {
			this.persona = persona0;
		}
		
		@Override
		public void run() {
			try { persona.esperarRevista(); } catch (InterruptedException e) { }
		}
	}
	
	public static void main(String[] args) {
		for (int i = 0; i < 20; i++) {
			new PersonaThread().start();
		}
	}

}
